package deployr.core;

import static java.text.MessageFormat.*;
import static java.util.Collections.*;

import java.util.*;

public class Checksum implements Iterable<String> {

	private Map<String, String> index = new HashMap<String, String>();

	public Checksum() {
	}

	public Checksum(Map<String, String> index) {
		this.index = unmodifiableMap(index);
	}

	public boolean contains(String pathOrHash) {
		return index.keySet().contains(pathOrHash) || index.values().contains(pathOrHash);
	}

	public Iterable<String> files() {
		return index.keySet();
	}

	public boolean isEmpty() {
		return index.isEmpty();
	}

	public String path(String hash) {
		for(String key: index.keySet()) {
			if(index.get(key).equals(hash)) return key;
		}
		return null;
	}

	public String hash(String path) {
		return index.get(path);
	}

	public Iterator<String> iterator() {
		return index.keySet().iterator();
	}

	public int size() {
		return index.size();
	}

	public Checksum merge(Checksum other) {
		Map<String, String> mergedIndex = new TreeMap<String, String>();
		mergedIndex.putAll(index);
		mergedIndex.putAll(other.index);
		return new Checksum(mergedIndex);
	}

	@Override
	public String toString() {
		StringBuilder toStringBuilder = new StringBuilder();
		append(index, toStringBuilder);
		return toStringBuilder.toString();
	}
	
	private void append(Map<String, String> updated, StringBuilder stringBuilder) {
		for (String path : updated.keySet()) {
			stringBuilder.append(format("{0}  {1}\n", updated.get(path), path));
		}
	}

}	